import os
import sys
import signal
import threading
from subprocess import Popen, PIPE
from .logging import loginfo


class Task(object):
    def __init__(self, executable, args, workdir = None, env = None):
        if workdir is None:
            workdir = os.getcwd()
        self.executable = executable
        self.args = args
        self.workdir = workdir
        self.env = env
        self.pid = None
        self.retcode = None
        self.proc = None
        self.stdout = None
        self.stderr = None
        self.__disposed = False
    
    def __repr__(self):
        return "<Task: %s %s>" % (self.executable, " ".join(self.args))
    
    def run(self):
        if self.__disposed:
            raise ValueError("process was already started")
        self.__disposed = True
        self.proc = subprocess.Popen(self.args, executable = self.executable,
            cwd = self.workdir, env = self.env, stdout = PIPE, stderr = PIPE, 
            close_fds = True, shell = False)
        self.pid = self.proc.pid
    
    def wait(self):
        if self.proc is None:
            raise ValueError("process is not running")
        self.retcode = self.proc.wait()
        self.stdout = self.proc.stdout.read()
        self.stderr = self.proc.stderr.read()
        self.proc = None
        self._finished.set()
    
    def is_running(self):
        if self.proc is None:
            return False
        if self.proc.poll() is not None:
            self.wait()
        return self.proc is not None
    
    def is_finished(self):
        if self.is_running():
            return False
        return self.__disposed


def run(executable, args, workdir = None, env = None):
    tsk = Task(executable, args, workdir = workdir, env = env)
    tsk.run()
    tsk.wait()
    return (tsk.retcode, tsk.stdout, tsk.stderr)

def add(executable, args, workdir = None, env = None):
    tsk = Task(executable, args, workdir = workdir, env = env)
    loginfo("TASK", tsk)
    return tsk

def wait_all():
    pass

















